//
//  DataRequestService.m
//  HappyMother
//
//  Created by yidong on 2017/10/23.
//  Copyright © 2017年 东哥. All rights reserved.
//

#import "DataRequestService.h"
#import "AFNetworking.h"

@implementation DataRequestService
+ (NSURLSessionDataTask *)requestURL:(NSString *)urlstring
                          httpMethod:(NSString *)method
                              params:(NSDictionary *)params
                          completion:(void(^)(id result,NSError *error))block {
    
    
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    
    [reachabilityManager startMonitoring];
    
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusNotReachable){
            //网络无连接的提示
            [MBProgressHUD showError:@"网络无连接" toView:nil];
            return ;
        }
        return;
        
    }];
    
    //1.拼接url
    //1.拼接URL
    NSString *url;
    
    url = [BASE_URL stringByAppendingString:urlstring];
    
    NSMutableString *mutableParmas = params.mutableCopy;
    if (mutableParmas == nil) {
        mutableParmas = @{}.mutableCopy;
    }
    
    //创建session对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json", nil];
    
    [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"clientType"];
    
    //判断请求方式
    if ([method caseInsensitiveCompare:@"GET"] == NSOrderedSame) {
        
        NSURLSessionDataTask *task = [manager GET:url parameters:mutableParmas progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            block(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            block(nil,error);
        }];
        
        return task;
    }
    else if ([method caseInsensitiveCompare:@"POST"] == NSOrderedSame) {
        
        NSURLSessionDataTask *task = [manager POST:url parameters:mutableParmas progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            block(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            block(nil,error);
        }];
        
        return  task;
    }
    else if ([method caseInsensitiveCompare:@"PUT"] == NSOrderedSame) {
        NSURLSessionDataTask *task = [manager PUT:url parameters:mutableParmas success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            block(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            block(nil,error);
        }];
        return task;
    }
    return nil;
}

@end
